package mint.modules.generator;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import org.antlr.runtime.tree.Tree;

import mint.modules.generator.expression.ExprNode;
import mint.modules.generator.expression.Expression;
import mint.modules.generator.expression.ExpressionType;
import mint.modules.type.Type;

public class WhileStmtNode extends Scope implements MintNode {
	private Expression expr;
	private BlockNode block;
	private int line;
	private List<String> errors;
	
	public WhileStmtNode(Scope theParent, Tree whileStmtTree) {
		super(theParent, theParent.containerClass);
		expr = new ExprNode(theParent, ExpressionType.Right, whileStmtTree.getChild(0));
		block = new BlockNode(theParent, whileStmtTree.getChild(1));
		line = whileStmtTree.getLine();
		errors = new ArrayList<String>();
	}

	@Override
	public void testSemantic() {
		expr.testSemantic();
		if (!expr.getType().equals(Type.booleanType))
			errors.add(line + ": expression in while statement must be boolean");
		block.testSemantic();
	}

	@Override
	public List<String> getSemanticErrors() {
		errors.addAll(expr.getSemanticErrors());
		errors.addAll(block.getSemanticErrors());
		return errors;
	}

	@Override
	public void emit(Formatter output) {
		String label1 = CounterManager.getInstance().generate("while");
		String label2 = CounterManager.getInstance().generate("while");		
		
		output.format("%s:\n", label1);
		expr.emit(output);
		output.format("ifeq %s\n", label2);
		block.emit(output);
		output.format("goto %s\n", label1);
		output.format("%s:\n", label2);
	}

	@Override
	public int getLine() {
		return line;
	}
	
	@Override
	public void printSymbolTable(Formatter output, int tabSize) {
		for (int i = 1; i <= tabSize; i++)
			output.format("\t");
		output.format("while:\n");
		block.printSymbolTable(output, tabSize + 1);
	}
}
